<template>
  <div class="baiduMark-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="layeredGraph-title">选择单位</div>
        <el-form :inline="true" ref="baiduMarkOrg" :model="baiduMarkOrg" @submit.native.prevent>
          <el-form-item style="width: 100%;">
            <el-select
              filterable
              style="width: 100%;"
              v-model="baiduMarkOrg.organizationId"
              @change="changeUnit()">
              <el-option
                v-for="item in baiduMarkOrg.data"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="13">
        <div class="layeredGraph-title">百度地图</div>
        <div class="baidu-map">
          <bmap-mark-model ref="bMap" v-on:newMarkPoint="newMarkPoint"></bmap-mark-model>
        </div>
      </el-col>
      <el-col :span="4">
        <div
          class="layeredGraph-title"
        >标注列表（共{{markAllData.filter(data => (!searchForm.name || data.name.toLowerCase().includes(searchForm.name.toLowerCase())) && (!searchForm.typeId || data.type==searchForm.typeId)).length}}个）</div>
        <el-form class="serach-form" ref="searchForm" :model="searchForm" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="searchForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item>
            <tree-select
              placeholder="请选择标注关联类型"
              v-model="searchForm.typeId"
              filterable
              :width="271"
              :data="typeList"
              :defaultProps="typeDefaultProps"
              :nodeKey="typeNodeKey"
            ></tree-select>
          </el-form-item>
        </el-form>
        <div
          class="relate-eq"
          :style="{
	  	  				width:100+'%',
	  	  				height:baiduMapObj.height+'px',
	  	  			}"
        >
          <el-table
            v-loading="baiduMarkTable.loading"
            :data="markAllData.filter(data => (!searchForm.name || data.name.toLowerCase().includes(searchForm.name.toLowerCase())) && (!searchForm.typeId || data.type==searchForm.typeId))"
            ref="baiduMarkTable"
          >
            <el-table-column label="名称" prop="name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="props">
                <el-button type="text" size="small" @click="fixPosition(props.row)">定位</el-button>
                <span class="dividing-line">|</span>
                <el-button type="text" size="small" @click="deleteMark(props.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="layeredGraph-title">百度地图标注关联类型</div>
        <el-collapse accordion>
          <el-collapse-item v-for="item in mark.groups" :title="item.tittle" :key="item.id">
            <el-radio
              class="mark-tool"
              v-for="val in item.node"
              v-model="currentMark.modelId"
              :key="val.id"
              :label="val.id"
              :icon="val.icon"
              @change="changeMarkType(val.id,val.icon,item.dictKey,val.name)"
            >{{ val.name }}</el-radio>
          </el-collapse-item>
        </el-collapse>
        <div class="layeredGraph-title is-required">标注名称</div>
        <el-input v-model="currentMark.name" placeholder="请输入标注名称"></el-input>
        <div class="layeredGraph-title">关联对象</div>
        <el-select
          v-show="currentMark.id != 2"
          v-model="relateEq.value"
          placeholder="请选择关联对象"
          filterable
          :filter-method="getFcfSelectList"
          :loading="relateEq.loading"
          @change="relateEqChange"
          id="relateEqFcf">
          <el-option value="">请选择关联对象</el-option>
          <el-option
            v-for="item in relateEq.data"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="relateEq.pageIndex"
            small
            layout="total, prev, pager, next"
            :total="relateEq.total"
          ></el-pagination>
        </el-select>
        <tree-select
					v-show="currentMark.id === 2"
					placeholder="请选择关联对象"
					v-model="relateBuildId"
					filterable
					:width="193"
					:data="relateBuildList"
					:defaultProps="relateBuildDefaultProps"
					:nodeKey="relateBuildNodeKey"
					@node-click="handleNodeClick">
				</tree-select>
        <div class="layeredGraph-title is-required">标注位置</div>
        <el-input v-model="currentMark.position" placeholder="请输入标注位置"></el-input>
        <el-button
          type="primary"
          style="float: right;margin-top: 10px;"
          @click="quitSaveBaiduMark()"
        >保存</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// let fengMap = null;
import bmapMarkModel from "./Pagemodel/BMarkMap";
import TreeSelect from "@/libs/TreeSelect/Main";
import {
  getMarkListByType,
  delMarkInfo,
  saveOrInsertMarkInfo,
  getRelationInfo
} from "@/api/baiduMark";
import { getOrgList, getFullInfoExt } from "@/api/org";
import { getDictByCode } from "@/api/dic";
import { getFcfSelectList } from "@/api/fcf";
import { getFbsTree } from "@/api/sysConfig";
import { debug } from "util";
import { delimiter } from "path";

export default {
  name: "BaiduMark",
  components: {
    TreeSelect,
    bmapMarkModel
  },
  data() {
    return {
      baiduMarkOrg: {
        data: [],
        organizationId: ""
      },
      firstLayer: null,
      firstAllLayer: null,
      imgSizeRate: 32, //图片大小缓存
      baiduMapObj: {
        tittle: "百度地图",
        loading: false,
        indooTypeName: "标注点类型",
        organizationId: 0,
        data: {},
        indoorId: "",
        height: top.window.document.body.clientHeight - 160,
        build: "",
        code57: []
      },
      mark: {
        groups: [],
        markClickType: ""
      },
      currentMark: {
        modelId: "",
        id: "",
        type: "",
        name: "",
        icon: "",
        lon: "",
        lat: "",
        position: ""
      },
      relateEq: {
        loading: false,
        value: "",
        pageIndex: 1,
        total: 0,
        data: []
      },
      fullLoading: false,
      searchForm: {
        name: "", // 搜索名称
        typeId: "" // 标注关联类型
      },
      typeList: [
        {
          id: "",
          name: "全部类别"
        }
      ],
      typeDefaultProps: {
        children: "node",
        label: "name",
        value: "id"
      },
      typeNodeKey: "id",
      relateBuildList: [], // 关联建筑物数据（当标注类型为建筑物时才用到）
			relateBuildDefaultProps: {
				children: 'nodes',
				label: 'text',
				value:'id'
			},
			relateBuildNodeKey: 'id',
			relateBuildId: '', // 关联建筑物id （当标注类型为建筑物时才用到）
      markAllData: [],
      isStartMark: false,
      baiduMarkTable: {
        loading: false,
        data: []
      },
      treeParentId: 0,
      iconMap: new Map()
    };
  },
  created() {
    let self = this;
    self.getMarkType();
    setTimeout(() => {
      self.bindOwnerUnit();
    }, 100);
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.text.indexOf(value) !== -1;
    },

    //获取标注点类型
    getMarkType() {
      let self = this;
      getDictByCode({ code: 58 }).then(data => {
        if (data) {
          self.baiduMapObj.indooTypeName = data.data.name;
          if (data.data.dictValueObj.length > 0) {
            for (let i = 0; i < data.data.dictValueObj.length; i++) {
              let obj = {};
              obj.id = data.data.dictValueObj[i].id;
              obj.tittle = data.data.dictValueObj[i].dictValue;
              obj.name = data.data.dictValueObj[i].dictValue;
              obj.dictKey = data.data.dictValueObj[i].dictKey;
              obj.node = [];
              self.mark.groups.push(obj);
            }
            getDictByCode({ code: 57 }).then(res => {
              if (res) {
                let resulte = res.data.dictValueObj[0];
                let dealResult = JSON.parse(resulte.dictValue);
                self.baiduMapObj.code57 = dealResult;
                for (let j = 0; j < self.mark.groups.length; j++) {
                  for (let m = 0; m < dealResult.length; m++) {
                    if (
                      self.mark.groups[j].dictKey == dealResult[m].relationType
                    ) {
                      let obj2 = {};
                      obj2.id = dealResult[m].id;
                      obj2.name = dealResult[m].name;
                      obj2.icon = dealResult[m].icon;
                      self.iconMap.set(obj2.id, obj2.icon);
                      self.mark.groups[j].node.push(obj2);
                    }
                  }
                }
                self.typeList = self.typeList.concat(self.mark.groups);
              }
            });
          }
        }
      });
    },
    //业主单位
    bindOwnerUnit: function() {
      let self = this;
      getOrgList({ queryType: 0 }).then(data => {
        if (data.data.length > 0) {
          self.baiduMarkOrg.organizationId = data.data[0].organizationId;
          self.changeUnit();
        }
        self.baiduMarkOrg.data = data.data;
      });
    },
    //切换业主单位
    changeUnit() {
      let self = this;
      self.markAllData=[]
      if(self.currentMark.id != 2) {
				// 重新获取关联对象
				self.getFcfSelectList()
			} else {
				// 获取关联建筑物
				self.getRelateBuildList()
			}
      self.showMarker();
      setTimeout(function() {
        self.getOrgInfo();
      }, 100);
    },
    handleCurrentChange(currentpage) {
      let self = this;
      self.relateEq.pageIndex = currentpage;
      self.getFcfSelectList($("#relateEqFcf .el-select__input").val(), true);
    },
    //获取联网单位坐标
    getOrgInfo() {
      let that = this;
      // 获取详细信息
      getFullInfoExt({
        organizationId: that.baiduMarkOrg.organizationId
      }).then(res => {
        that.baseInfo = res.data;
        // 初始化地图
        if (res.data.longitude && res.data.latitude) {
          that.$refs["bMap"].fixedTypeCenter(
            res.data.longitude,
            res.data.latitude
          );
        }
      });
    },
    /*获取关联物联设备*/
    getFcfSelectList(name, pageChange) {
      let self = this;
      // 重新搜索时页码复原
      if (!pageChange) {
        this.relateEq.pageIndex = 1;
      }
      if (self.currentMark.id) {
        self.relateEq.loading = true;
        let parames = {
          queryType: 1,
          orgId: self.baiduMarkOrg.organizationId,
          fbsId: self.baiduMapObj.build || 0,
          type: self.currentMark.id || "",
          name: name || "",
          pageIndex: self.relateEq.pageIndex - 1,
          pageSize: 10
        };
        getRelationInfo(parames).then(data => {
          //vr
					if(self.currentMark.id == 30){
						data.data.forEach(item=>{
							item.id = item.remark
						})
					}
          self.relateEq.data = data.data;
          self.relateEq.total = data.total;
          self.relateEq.loading = false;
        });
      }
    },
    relateEqChange(val) {
      let obj = {};
      obj = this.relateEq.data.find(item => {
        return item.id === val;
      });
      this.currentMark.name = obj.name;
    },
    // 获取关联建筑物数据
		getRelateBuildList() {
			let self = this
			self.relateBuildId = ''
			getFbsTree({
        organizationId: self.baiduMarkOrg.organizationId
			}).then((data)=>{
			    if(data.status == 200){
			        self.relateBuildList = data.data;
			    }
			});
		},
		handleNodeClick(obj, node, item) {
			let nameStr = obj.text
			let nameSum = (ele) => {
				if(ele.parent.level > 1) {
          nameStr = ele.parent.data.text + '>' + nameStr
					nameSum(ele.parent)
				}
			}
			// 计算中文名称
			nameSum(node)
			this.currentMark.name = nameStr
		},
    // 获取经纬度
    newMarkPoint(lon, lat, addr, type) {
      let that = this;
      that.currentMark.lon = lon;
      that.currentMark.lat = lat;
      that.currentMark.position = addr;
      that.currentMark.type = type;
    },
    //获取标注列表
    showMarker: function(isAdd) {
      let self = this;
      getMarkListByType({
        orgIds: self.baiduMarkOrg.organizationId,
        queryType: 0,
        pageIndex: 0,
        pageSize: 0,
        queryContent: ""
      }).then(data => {
        if (data.status == 200) {
          if (data.data) {
            data = data.data;
            let newArr = [];
            for (let i = 0; i < data.length; i++) {
              let obj = {};
              obj.id = data[i].id;
              obj.lat = data[i].lat;
              obj.lon = data[i].lon;
              obj.name = data[i].name;
              obj.type = data[i].type;
              newArr.push(obj);
            }
            self.markAllData = newArr;
            setTimeout(() => {
              self.showAllMark();
            }, 500);
          }
        }
      });
    },
    //展示标注点
    showAllMark() {
      let self = this;
      self.fullLoading = this.$loading({
        lock: true,
        text: "展示标注点...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      self.$refs["bMap"].clearMarkPoint();
      for (let i = 0; i < self.markAllData.length; i++) {
        self.$refs["bMap"].addSavedMarker(
          self.markAllData[i].lon,
          self.markAllData[i].lat,
          self.markAllData[i].type,
          self.iconMap.get(self.markAllData[i].type)
        );
      }
      self.fullLoading.close();
      if(self.isStartMark){
        self.$refs["bMap"].setdrawingType(true);
      }
    },
    changeMarkType(id, icon, dictKey, name) {
      let self = this;
      this.$message({
        message: "开启标点",
        type: "success"
      });
      self.$refs["bMap"].setdrawingType(true);
      self.$refs["bMap"].type = dictKey;
      self.$refs["bMap"].icon = icon;
      self.currentMark.modelId = id;
      self.currentMark.id = id;
      self.currentMark.name = "";
      self.currentMark.icon = icon;
      self.currentMark.type = dictKey;
      self.isStartMark = true;
      // 重置关联对象
      self.relateEq.value = "";
      if(self.currentMark.id != 2) {
				// 重新获取关联对象
				self.getFcfSelectList()
			} else {
				// 获取关联建筑物
				self.getRelateBuildList()
			}
    },
    //定位
    fixPosition(value) {
      let self = this;
      self.$refs["bMap"].pointCenter(value.lon, value.lat);
    },
    //删除
    deleteMark(value) {
      let self = this;
      // 阻止事件冒泡
      event.stopPropagation();
      if (value) {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          roundButton: true
        })
          .then(() => {
            delMarkInfo({ id: value.id }).then(data => {
              if (data.status === 200) {
                self.$message({
                  message: "删除成功",
                  type: "success"
                });
                self.currentMark.name = "";
                self.currentMark.position = "";
                self.relateEq.value = "";
                setTimeout(() => {
                  self.$refs["bMap"].setdrawingType(true);
                }, 100);
                //获取标注点数据
                self.showMarker(true);
              }
            });
            // 阻止事件冒泡
            event.stopPropagation();
          })
          .catch(() => {});
      }
    },
    //保存打点
    quitSaveBaiduMark() {
      let self = this;
      //标注点type
      if (!self.isStartMark) {
        self.$message({
          message: "未开启标点",
          type: "warning"
        });
      }
      if (self.currentMark.name.trim() == "") {
        self.$message({
          message: "请输入标注名称",
          type: "warning"
        });
        return;
      }
      if (self.currentMark.position.trim() == "") {
        self.$message({
          message: "请输入标注位置",
          type: "warning"
        });
        return;
      }
      let param = {
        type: self.currentMark.id,
        orgId: self.baiduMarkOrg.organizationId,
        platId: 0,
        bizId: self.relateEq.value.toString(), //消防设施
        lon: self.currentMark.lon,
        lat: self.currentMark.lat,
        name: self.currentMark.name,
        location: self.currentMark.position,
        name: self.currentMark.name,
        typeGroup: Number(self.currentMark.type)
      };
      // 建筑物
      if(self.currentMark.id == 2){ 
				param.bizId = self.relateBuildId || ''
			}
      saveOrInsertMarkInfo(param).then(res => {
        if (res.status === 200) {
          self.$message({
            message: "标注成功",
            type: "success"
          });
          self.currentMark.name = "";
          self.currentMark.position = "";
          self.relateEq.value = "";
          setTimeout(() => {
            self.$refs["bMap"].setdrawingType(true);
          }, 100);
          //获取标注点数据
          self.showMarker(true);
        }
      });
    },
    //清除某一个标注点
    cleanOneMark(obj) {
      let self = this;
      let index = -1;
      if (self.markAllData.length > 0) {
        for (let i = 0; i < self.markAllData.length; i++) {
          if (obj.id == self.markAllData[i].id_) {
            self.firstAllLayer.removeMarker(self.markAllData[i]);
            index = i;
          }
        }
        if (index > -1) {
          self.markAllData.splice(index, 1);
        }
      }
    }
  }
};
</script>

<style lang="less">
.baiduMark-container {
  .layeredGraph-title {
    font-weight: bold;
    padding: 10px;
    background-color: #f7f7f7;
    &.is-required::before {
      content: "*";
      color: #f56c6c;
      margin-right: 4px;
    }
  }
  .el-form-item__content {
    width: 100%;
    margin-left: auto !important;
  }
  .baidu-map,
  .relate-eq {
    border: 1px solid rgba(238, 238, 238, 0.9);
    border-top: none;
  }
  .relate-eq {
    overflow: auto;
  }
  .mark-tool {
    width: 100%;
  }
}
</style>